<template>
  <div>
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :viewFunc="handleView"
        :delFunc="handleDelete"
        :total="page.total"
        :page-count="page.pageCount"
        :current-page="page.currentPage"
        :page-size="page.size"
        :changePage="changePage"
        :handle-size-change="handleSizeChange"
        :editFunc="handleEdit"
        :refresh="getData"
        style="height: calc(100vh - 300px);"
      >
        <template #toolbarBtn>
          <el-button type="warning" :icon="CirclePlusFilled" @click="visible = true">新增</el-button>
        </template>
      </TableCustom>
    </div>
    <el-dialog
      :title="isEdit ? '编辑' : '新增'"
      v-model="visible"
      width="700px"
      destroy-on-close
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <!-- 替换TableEdit组件为自定义表单 -->
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="序号" prop="id">
              <el-input v-model="form.id" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="楼栋编号" prop="buildingCode">
              <el-select
                v-model="form.buildingCode"
                placeholder="请选择楼栋编号"
                clearable
                filterable
                @change="handleBuildingChange"
              >
                <el-option
                  v-for="opt in buildingOptions"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁层数" prop="floors">
              <el-select
                v-model="form.floors"
                placeholder="请选择租赁层数"
                clearable
                multiple
              >
                <el-option-group
                  v-for="group in floorOptionGroups"
                  :key="group.label"
                  :label="group.label"
                >
                  <el-option
                    v-for="opt in group.options"
                    :key="opt.value"
                    :label="opt.label"
                    :value="opt.value"
                    :disabled="opt.disabled"
                  ></el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                type="date"
                v-model="form.startDate"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker
                type="date"
                v-model="form.endDate"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月租金(元)" prop="rent">
              <el-input v-model="form.rent" placeholder="请输入月租金"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="免租金(月)" prop="freeRent">
              <el-input v-model="form.freeRent" placeholder="请输入免租金(月)"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="承租方" prop="rentName">
              <el-input v-model="form.rentName" placeholder="请输入承租方"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="saveEdit(formRef)">保 存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
      <TableDetail :data="viewData"></TableDetail>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="loan-management">
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import {
  fetchBuildingRentalData,
  saveBuildingRentalData,
  delBuildingRentalDataById,
  fetchBuildingData,
  fetchBuildingRentalDataByCode,
  fetchBuildingRentalDataById
} from '@/api';

import TableCustom from '@/components/table-custom.vue';
import TableDetail from '@/components/table-detail.vue';
import { FormOption, FormOptionList } from '@/types/form-option';

// 表格相关
let columns = ref([
  { type: 'id', prop: 'id', label: '序号', width: 55, align: 'center' },
  { prop: 'buildingCode', label: '楼栋编号' },
  { prop: 'floors', label: '租赁层数' },
  { prop: 'startDate', label: '开始时间' },
  { prop: 'endDate', label: '结束时间' },
  { prop: 'rent', label: '月租金(元)' },
  { prop: 'freeRent', label: '免租金(月)' },
  { prop: 'rentName', label: '承租方' },
  { prop: 'operator', label: '操作', width: 250 }
]);

onMounted(async () => {
  const res = await fetchBuildingData(1, 1000);
  buildingOptions.value = res.data.content.map(item => ({
    label: item.buildingCode,
    value: item.buildingCode
  }));
  
  // 初始化楼层选项
  floorOptions.value = Array.from({ length: 30 }, (_, i) => ({
    label: `${i + 1}层`,
    value: i + 1
  }));
});

const changePage = (val: number) => {
  page.index = val;
  page.currentPage = val;
  getData();
};

const handleSizeChange = (val: number) => {
  page.size = val;
  page.index = 1;
  page.currentPage = 1;
  getData();
};

const page = reactive({
  total: 0,
  index: 1,
  size: 50,
  hasPagination: true,
  layout: 'prev, pager, next,total',
  currentPage: 1,
  pageCount: 1,
  

});
const tableData = ref<[]>();
const getData = async () => {
  const res = await fetchBuildingRentalData(page.index, page.size);
  tableData.value = res.data.content;
  tableData.value.forEach((item, index) => {
    item.labelId = index + 1 + (page.index - 1) * page.size;
  })
  page.index = res.data.number + 1;
  page.total = res.data.totalElements;
  page.size = res.data.size;
  page.pageCount = res.data.totalPages;
};

const saveCompany = async (data) => {
  // 这里可以添加调用API的逻辑来新增公司
  await saveBuildingRentalData(data);

  getData();
};

const delBuildingData = async (id) => {
  // 这里可以添加调用API的逻辑来新增公司
  await delBuildingRentalDataById(id);

  getData();
};
getData();

// 新增/编辑弹窗相关
const visible = ref(false);
const isEdit = ref(false);
const form = ref({
  id: '',
  buildingCode: '',
  floors: [],
  rent: '',
  freeRent: '',
  totalRent: '',
  startDate: '',
  endDate: '',
  rentName: ''
});

// 表单验证规则
const rules = reactive<FormRules>({
  buildingCode: [{ required: true, message: '楼栋编号不能为空', trigger: 'blur' }],
  floors: [{ required: true, message: '租赁层数不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
  rent: [{ required: true, message: '月租金不能为空', trigger: 'blur' }],
  freeRent: [{ required: true, message: '免租金不能为空', trigger: 'blur' }],
  rentName: [{ required: true, message: '承租方不能为空', trigger: 'blur' }]
});

const formRef = ref<FormInstance>();

// 楼栋选项
const buildingOptions = ref([]);
// 楼层选项
const floorOptions = ref([]);
// 楼层选项分组
const floorOptionGroups = ref([
  { label: '未租', options: [] },
  { label: '已租', options: [] }
]);


const rowData = ref({});
const handleEdit = (row) => {
  rowData.value = { ...row };
  form.value = { ...row };
  isEdit.value = true;
  visible.value = true;
  rentId.value = row.id;

  // 编辑时更新楼层选项
  if (row.buildingCode) {
    handleBuildingChange(row.buildingCode);
  }
};

const updateData = async (data) => {
  await saveCompany(data);
  if (!isEdit.value) {
    ElMessage.success('新增成功');
  } else {
    ElMessage.success('编辑成功');
  }
  closeDialog();
  getData();
};

const saveEdit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      updateData(form.value);
    }
  });
};

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
  form.value = {
    id: '',
    buildingCode: '',
    floors: [],
    rent: '',
    startDate: '',
    endDate: '',
    rentName: ''
  };
};

const rentId = ref(0);

// 处理楼栋选择变化
const handleBuildingChange = async (value) => {
  // 保存当前已选择的楼层
  const selectedFloors = [...form.value.floors];
  
  // 清空已选的楼层
  form.value.floors = [];
  
  if (value) {
    // 获取已租楼层
    const rentInfo = isEdit.value ? 
    await fetchBuildingRentalDataById(rentId.value) : 
    await fetchBuildingRentalDataByCode(value);

    const rentedFloors = rentInfo.data.floors;
    
    const allFloors = Array.from({ length: rentInfo.data.floorCount }, (_, i) => ({
      label: `${i + 1}层`,
      value: i + 1
    }));
    
    // 从未租楼层中过滤出当前已选择的楼层
    const availableFloors = allFloors.filter(floor => !rentedFloors.includes(floor.value));
    
    // 将当前已选择的楼层添加到未租楼层组中
    const currentSelectedFloors = selectedFloors.map(floor => ({
      label: `${floor}层`,
      value: floor,
      disabled: false
    }));
    
    floorOptionGroups.value = [
      { 
        label: '未租', 
        options: [...currentSelectedFloors, ...availableFloors.filter(floor => !selectedFloors.includes(floor.value))]
      },
      { 
        label: '已租', 
        options: allFloors.filter(floor => rentedFloors.includes(floor.value)).map(floor => ({ ...floor, disabled: true }))
      }
    ];
    
    // 自动勾选当前已选择的楼层
    form.value.floors = selectedFloors;
  }
};

// // 处理楼栋选择变化
// const handleBuildingChange = async (value) => {
//   // 清空已选的楼层
//   form.value.floors = [];
  
//   if (value) {
//     // 获取已租楼层
//     const rentInfo = isEdit.value ? 
//     await fetchBuildingRentalDataById(rentId.value) : 
//     await fetchBuildingRentalDataByCode(value);

//     const rentedFloors = rentInfo.data.floors;
    
//     const allFloors = Array.from({ length: rentInfo.data.floorCount }, (_, i) => ({

//       label: `${i + 1}层`,
//       value: i + 1
//     }));
    
//     floorOptionGroups.value = [
//       { 
//         label: '未租', 
//         options: allFloors.filter(floor => !rentedFloors.includes(floor.value))
//       },
//       { 
//         label: '已租', 
//         options: allFloors.filter(floor => rentedFloors.includes(floor.value)).map(floor => ({ ...floor, disabled: true }))
//       }
//     ];
//   }
// };

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: []
});
const handleView = (row) => {
  viewData.value.row = { ...row };
  viewData.value.list = [
    { type: 'id', prop: 'id', label: '序号' },
    { prop: 'buildingCode', label: '楼栋编号' },
    { prop: 'floors', label: '租赁层数' },
    { prop: 'startDate', label: '开始时间' },
    { prop: 'endDate', label: '结束时间' },
    { prop: 'rent', label: '月租金(元)' },
    { prop: 'freeRent', label: '免租金(月)' },
    { prop: 'rentName', label: '承租方' }
  ];
  visible1.value = true;
};

// 删除相关
const handleDelete = (row) => {
  delBuildingData(row.id);
  ElMessage.success('删除成功');
};
</script>

<style scoped>
.container {
    height: calc(100vh - 200px);
}

</style>